//
//  SGdownloader.m
//  downloadManager
//
//  Created by saturngod on 11/7/12.
//

#import "HCSGdownloader.h"

@interface HCSGdownloader()
@property (nonatomic,assign) float receiveBytes;
@property (nonatomic,assign) float exceptedBytes;
@property (nonatomic,strong) NSURLRequest *request;
@property (nonatomic,strong) NSURLConnection *connection;

//for block
@property (nonatomic,strong) HCSGDownloadProgressBlock progressDownloadBlock;
@property (nonatomic,strong) HCSGDowloadFinished progressFinishBlock;
@property (nonatomic,strong) HCSGDownloadFailBlock progressFailBlock;

@end

@implementation HCSGdownloader
@synthesize receiveData = _receiveData;
@synthesize request = _request;
@synthesize connection = _connection;
@synthesize downloadedPercentage = _downloadedPercentage;
@synthesize receiveBytes;
@synthesize exceptedBytes;
@synthesize progress = _progress;
@synthesize progressFailBlock = _progressFailBlock;
@synthesize progressDownloadBlock = _progressDownloadBlock;
@synthesize progressFinishBlock = _progressFinishBlock;
@synthesize delegate = _delegate;

-(id)initWithURL:(NSURL *)fileURL timeout:(NSInteger)timeout{
    
    
    self = [super init];
    
    if(self)
    {
        self.receiveBytes = 0;
        self.exceptedBytes = 0;
        _receiveData = [[NSMutableData alloc] initWithLength:0];
        _downloadedPercentage = 0.0f;
        self.request = [[NSURLRequest alloc] initWithURL:fileURL cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:timeout];
    
        
        self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO];
        

        
    }
    
    return self;
}

#pragma mark - NSURLConnectionDataDelegate

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [_receiveData appendData:data];
    NSInteger len = [data length];
    receiveBytes = receiveBytes + len;
    
    if(exceptedBytes != NSURLResponseUnknownLength) {
        _progress = ((receiveBytes/(float)exceptedBytes) * 100)/100;
        _downloadedPercentage = _progress * 100;
        
        if(self.flag == 0)
        {
            if([_delegate respondsToSelector:@selector(HCSGDownloadProgress:Percentage:)])
            {
                [_delegate HCSGDownloadProgress:_progress Percentage:_downloadedPercentage];
            }
            else {
                if(_progressDownloadBlock) {
                    _progressDownloadBlock(_progress,_downloadedPercentage);
                }
            }
        }
        else if(self.flag == 1)
        {
            if([_delegate respondsToSelector:@selector(HCSGDownloadProgress2:Percentage2:)])
            {
                [_delegate HCSGDownloadProgress2:_progress Percentage2:_downloadedPercentage];
            }
            else {
                if(_progressDownloadBlock) {
                    _progressDownloadBlock(_progress,_downloadedPercentage);
                }
            }
        }
        else if(self.flag == 2)
        {
            if([_delegate respondsToSelector:@selector(HCSGDownloadProgress3:Percentage3:)])
            {
                [_delegate HCSGDownloadProgress3:_progress Percentage3:_downloadedPercentage];
            }
            else {
                if(_progressDownloadBlock) {
                    _progressDownloadBlock(_progress,_downloadedPercentage);
                }
            }
        }
        else if(self.flag == 3)
        {
            if([_delegate respondsToSelector:@selector(HCSGDownloadProgress4:Percentage4:)])
            {
                [_delegate HCSGDownloadProgress4:_progress Percentage4:_downloadedPercentage];
            }
            else {
                if(_progressDownloadBlock) {
                    _progressDownloadBlock(_progress,_downloadedPercentage);
                }
            }
        }
        else if(self.flag == 4)
        {
            if([_delegate respondsToSelector:@selector(HCSGDownloadProgress5:Percentage5:)])
            {
                [_delegate HCSGDownloadProgress5:_progress Percentage5:_downloadedPercentage];
            }
            else {
                if(_progressDownloadBlock) {
                    _progressDownloadBlock(_progress,_downloadedPercentage);
                }
            }
        }
        else
        {
            if([_delegate respondsToSelector:@selector(HCSGDownloadProgress6:Percentage6:)])
            {
                [_delegate HCSGDownloadProgress6:_progress Percentage6:_downloadedPercentage];
            }
            else {
                if(_progressDownloadBlock) {
                    _progressDownloadBlock(_progress,_downloadedPercentage);
                }
            }
        }
    }
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    //return back error
    if([_delegate respondsToSelector:@selector(HCSGDownloadFail:)])
    {
        [_delegate HCSGDownloadFail:error];
    }
    else {
        if(_progressFailBlock) {
            _progressFailBlock(error);
        }
    }
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    exceptedBytes = [response expectedContentLength];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    self.connection = nil;
    
    if(self.flag == 0)
    {
        if([_delegate respondsToSelector:@selector(HCSGDownloadFinished:)])
        {
            [_delegate HCSGDownloadFinished:_receiveData];
        }
        else {
            if(_progressFinishBlock) {
                _progressFinishBlock(_receiveData);
            }
        }
    }
    else if(self.flag == 1)
    {
        if([_delegate respondsToSelector:@selector(HCSGDownloadFinished2:)])
        {
            [_delegate HCSGDownloadFinished2:_receiveData];
        }
        else {
            if(_progressFinishBlock) {
                _progressFinishBlock(_receiveData);
            }
        }
    }
    else if(self.flag == 2)
    {
        if([_delegate respondsToSelector:@selector(HCSGDownloadFinished3:)])
        {
            [_delegate HCSGDownloadFinished3:_receiveData];
        }
        else {
            if(_progressFinishBlock) {
                _progressFinishBlock(_receiveData);
            }
        }
    }
    else if(self.flag == 3)
    {
        if([_delegate respondsToSelector:@selector(HCSGDownloadFinished4:)])
        {
            [_delegate HCSGDownloadFinished4:_receiveData];
        }
        else {
            if(_progressFinishBlock) {
                _progressFinishBlock(_receiveData);
            }
        }
    }
    else if(self.flag == 4)
    {
        if([_delegate respondsToSelector:@selector(HCSGDownloadFinished5:)])
        {
            [_delegate HCSGDownloadFinished5:_receiveData];
        }
        else {
            if(_progressFinishBlock) {
                _progressFinishBlock(_receiveData);
            }
        }
    }
    else
    {
        if([_delegate respondsToSelector:@selector(HCSGDownloadFinished6:)])
        {
            [_delegate HCSGDownloadFinished6:_receiveData];
        }
        else {
            if(_progressFinishBlock) {
                _progressFinishBlock(_receiveData);
            }
        }
    }
}

#pragma mark - properties
-(void)startWithDelegate:(id<HCSGdownloaderDelegate>)delegate {
    _delegate = delegate;
    if(self.connection) {
        [self.connection start];
        _progressDownloadBlock= nil;
        _progressFinishBlock = nil;
        _progressFailBlock = nil;
    }
}
-(void)startWithDownloading:(HCSGDownloadProgressBlock)progressBlock onFinished:(HCSGDowloadFinished)finishedBlock onFail:(HCSGDownloadFailBlock)failBlock {
    if(self.connection) {
        [self.connection start];
        _delegate = nil; //clear delegate
        _progressDownloadBlock = [progressBlock copy];
        _progressFinishBlock = [finishedBlock copy];
        _progressFailBlock = [failBlock copy];
    }
    
}
-(void)cancel {
    if(self.connection) {
        [self.connection cancel];
    }
}
@end
